<template>
  <!-- 评论 -->
  <div class="comment_container">
    <!-- 我的评论 -->
    <div class="my_comment_wrapper">
      <div class="left_user_avatar">
        <img
          :src="userAvatarUrl?userAvatarUrl:'http://s4.music.126.net/style/web2/img/default/default_avatar.jpg?param=50y50'"
          alt="">
      </div>
      <div class="right_text_input">
        <el-input maxlength="140" placeholder="请输入评论内容" show-word-limit type="textarea" :rows="4" v-model="content" />
        <div class="btn_comment">
          <el-button type="primary" @click="handleClickComment">评论</el-button>
        </div>
      </div>
    </div>
    <!-- 评论 -->
    <div class="foucs_comment_wrapper" v-for="(el,i) in playlist" :key="i">
      <div class="foucs_title" v-show="el && el.length > 0">{{ i === 0 ? '精彩评论' : `最新评论（${total}）`}}</div>
      <div class="user_comment_item" v-for="(item, index) in el" :key="index">
        <div class="left_user_comment_avatar cursor_class"
          @click="()=>{router.push({name:'user-home',params:{id:item.user.userId}})}">
          <img :src="item.user.avatarUrl" alt="">
        </div>
        <div class="right_user_comment_contnent">
          <div class="top_info">
            <el-link type="primary" @click="()=>{router.push({name:'user-home',params:{id:item.user.userId}})}">{{
            item.user.nickname }}</el-link>
            <span style="margin: 0 10px;">:</span>
            <span class="comment_text">
              {{ item.content }}
            </span>
          </div>
          <div v-for="(ele, key) in item.beReplied" :key="index" class="middle_info">
            <el-link type="primary">{{ ele.user.nickname }}</el-link>
            <span style="margin: 0 10px;">:</span>
            <span class="comment_text">
              {{ ele.content }}
            </span>
          </div>
          <div class="bottom_info">
            <div class="left_time"
              v-if="commentType === 0 || commentType === 2 || commentType === 3 || commentType=== 4">{{i === 0 ?
              dayjs(item.time).format('YYYY年M月D日') :
              dayjs(item.time).format('M月D日 HH:mm')}}</div>
            <div class="left_time" v-if="commentType === 1">{{ item.timeStr }}</div>
            <div class="right_esb_wrap">
              <template v-if="item.user.userId === userInfo.userId">
                <el-button link style="margin-right:10px" type="danger" @click="handleClickDeleteReply(item.commentId)">
                  删除</el-button>
              </template>
              <div class="right_esb cursor_class">
                <el-button :icon="Pointer" link type="primary" @click="hanleClickLike(item.commentId,item.liked)">
                </el-button>
                <span>({{ item.likedCount }})</span>
              </div>
              <span style="margin:0 10px;color:#999">|</span>
              <el-button link @click="handleClickReply(item.commentId)">回复</el-button>
            </div>
          </div>
          <!-- 回复组件 -->
          <div v-if="controlCommentShowScope && item.commentId==controlCommentId">
            <Reply :nickName="item.user.nickname" @handleClickCloseReply="handleClickCloseReply"
              @handleClickReplySecond="handleClickReplySecond($event,item.commentId)" :contents="contents" />
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 登录注册弹窗 -->
  <LoginAndRegister ref="loginAndRegisterRef" />
</template>
<script lang="ts" setup>
import {
  Plus, Timer, VideoPlay, Comment, FolderAdd, Pointer
} from '@element-plus/icons-vue'
import * as commentApi from '@/api/comment'
import { onMounted, ref, toRefs, watch, reactive, getCurrentInstance } from 'vue'
import Reply from "@/components/Reply";
import dayjs from "dayjs";
import router from '@/router';
import { ElMessage, ElMessageBox } from 'element-plus'
import { loginAndRegisterTypeRef } from "@/types/login";
import LoginAndRegister from '@/components/LoginAndRegister/index'
const loginAndRegisterRef = ref<loginAndRegisterTypeRef | null>()
const { proxy }: any = getCurrentInstance()
const playlist = reactive<any[]>([
  [],
  []
])
const userInfo = ref<any>({})
const userAvatarUrl = ref('')
// 控制评论回复框的显示与隐藏
const controlCommentShowScope = ref(false)
// 评论id
const controlCommentId = ref<any>(null)
// 最新评论总数
const total = ref(0)
// 评论回复记录点击次数
const v = ref(1)
//  t:1 发送, 2 回复
const t = ref<number>(1)
const type = ref<number>(0)
const commentIdData = ref<number | null>(null)
const content = ref<string>('')
const contents = ref<string>('')
const likeParams = reactive<any>({
  id: 0,
  cid: 0,
  t: 1,
  type: 0,
  threadId: null
})
const props = defineProps({
  id: {
    type: [String, Number],
    default: 0
  },
  // 获取最新评论数量
  playlistLimit: {
    type: Number,
    default: 20
  },
  // 当前页
  pageNum: {
    type: Number,
    default: 1
  },
  // 是否为动态id 即：传递的id是会变的  带id详情页的id是不会变的，也就是说是不会执行watch函数
  isActiveId: {
    type: Boolean,
    default: true,
  },
  // 获取的评论类型，0：歌单，1：动态,2:歌曲,3:专辑 ;4：mv
  commentType: {
    type: Number,
    default: 0,
  }
})
const { id, playlistLimit, pageNum, commentType } = toRefs(props)
const emit = defineEmits(['getTotal'])
watch(id, (newData, oldData) => {
  init()
});
watch(pageNum, async (newData, oldData) => {
  init()
  // 切换页数关闭评论框
  handleClickCloseReply()
});
const init = async () => {
  switch (commentType.value) {
    case 0:
      // 全部评论
      getAllComment()
      break;
    case 1:
      // 关注评论
      getEventComment()
      break;
    case 2:
      // 歌曲评论
      musicComment()
      break;
    case 3:
      // 专辑评论
      albumCommet()
      break;
    case 4:
      // mv评论
      mvsCommet()
      break;
    default:
      break;
  }
}
//  全部评论
const getAllComment = async () => {
  const data: any = await commentApi.playlist({ id: id.value, offset: (pageNum.value - 1) * playlistLimit.value, limit: playlistLimit.value })
  playlist[0] = data.hotComments
  playlist[1] = data.comments
  total.value = data.total
  emit('getTotal', data.total)
}
// 关注评论
const getEventComment = async () => {
  const data2: any = await commentApi.event({ threadId: id.value, offset: (pageNum.value - 1) * playlistLimit.value, limit: playlistLimit.value })
  playlist[0] = data2.hotComments
  playlist[1] = data2.comments
  total.value = data2.total
  emit('getTotal', data2.total)
}
// 歌曲评论
const musicComment = async () => {
  const data3: any = await commentApi.musicComment({ id: id.value, offset: (pageNum.value - 1) * playlistLimit.value, limit: playlistLimit.value })
  playlist[0] = data3.hotComments
  playlist[1] = data3.comments
  total.value = data3.total
  emit('getTotal', data3.total)
}
// 专辑评论
const albumCommet = async () => {
  const data4: any = await commentApi.albumCommet({ id: id.value, offset: (pageNum.value - 1) * playlistLimit.value, limit: playlistLimit.value })
  playlist[0] = data4.hotComments
  playlist[1] = data4.comments
  total.value = data4.total
  emit('getTotal', data4.total)
}
// mv评论
const mvsCommet = async () => {
  const data5: any = await commentApi.mvsCommet({ id: id.value, offset: (pageNum.value - 1) * playlistLimit.value, limit: playlistLimit.value })
  playlist[0] = data5.hotComments
  playlist[1] = data5.comments
  total.value = data5.total
  emit('getTotal', data5.total)
}
// 如果不是动态id 就执行一次init
if (!props.isActiveId) {
  init()
}
// 评论回复
const handleClickReply = (commentId: number) => {
  if (v.value === 1) {  // 如果是第一次点击😁
    controlCommentShowScope.value = true
    controlCommentId.value = commentId
    v.value = 2
  } else if (v.value === 2 && controlCommentId.value === commentId) {  // 第二次点击是同一个人那么再次点击回复就隐藏回复框 😁
    controlCommentShowScope.value = false
    v.value = 1
  } else if (v.value === 2 && controlCommentId.value !== commentId) {  // 第二次点击不是同一个人的话显示输入框😁
    controlCommentShowScope.value = true
    controlCommentId.value = commentId
    v.value = 2
  }
  console.log(v.value);


  // controlCommentShowScope.value = !controlCommentShowScope.value
  // controlCommentShowScope.value = true
  // if(!controlCommentShowScope.value) handleClickCloseReply()
  // console.log( controlCommentShowScope.value);

}
// 关闭评论框
const handleClickCloseReply = () => {
  controlCommentId.value = null
  controlCommentShowScope.value = false
}
try {
  userInfo.value = proxy.$getUserInfo()
  if (userInfo.value.avatarUrl) {
    userAvatarUrl.value = userInfo.value.avatarUrl
  }
} catch (error) {
  userInfo.value = {}
}
// 评论
const handleClickComment = () => {
  commentData(1)
}
// 二级评论回复
const handleClickReplySecond = (e: string, commentId: number) => {
  contents.value = e
  commentIdData.value = commentId
  commentData(2)
}
// 删除评论
const handleClickDeleteReply = (commentId: number) => {
  ElMessageBox.confirm(
    '确定删除该评论吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      commentIdData.value = commentId
      commentData(3)
    })
    .catch(() => {
    })
}
// 回复评论
const commentData = async (num: number) => {
  let cookie = localStorage.getItem('cookie')
  if (cookie) {
    try {
      if (commentType.value === 1) {
        type.value = 6
      } else if (commentType.value === 2) {
        type.value = 0
      } else if (commentType.value === 3) {
        type.value = 3
      } else if (commentType.value === 4) {
        type.value = 5
      } else if (commentType.value === 0) {
        type.value = 2
      }
      let params = null
      if (num === 1) {
        // 一级 评论
        t.value = 1
        if (commentType.value === 1) {
          params = {
            t: t.value,
            type: type.value,
            threadId: id.value,
            cookie,
            content: content.value
          }
        } else {
          params = {
            t: t.value,
            type: type.value,
            id: id.value,
            cookie,
            content: content.value
          }
        }

      } else if (num === 2) {
        t.value = 2
        if (commentType.value === 1) {
          params = {
            t: t.value,
            type: type.value,
            threadId: id.value,
            cookie,
            content: contents.value,
            commentId: commentIdData.value
          }
        } else {
          params = {
            t: t.value,
            type: type.value,
            id: id.value,
            cookie,
            content: contents.value,
            commentId: commentIdData.value
          }
        }
      } else if (num === 3) {
        t.value = 0
        if (commentType.value === 1) {
          params = {
            t: t.value,
            type: type.value,
            threadId: id.value,
            cookie,
            commentId: commentIdData.value
          }
        } else {
          params = {
            t: t.value,
            type: type.value,
            id: id.value,
            cookie,
            commentId: commentIdData.value
          }
        }

      }
      const res: any = await commentApi.commet(params)
      if (res.code === 200) {
        if (num === 1) {
          ElMessage({
            type: 'success',
            message: '评论成功',
            duration: 2000
          })
        } else if (num === 2) {
          ElMessage({
            type: 'success',
            message: '回复成功',
            duration: 2000
          })
          controlCommentShowScope.value = false
          v.value = 1
        } else if (num === 3) {
          ElMessage({
            type: 'success',
            message: '删除成功',
            duration: 2000
          })
        }
      }
      if (commentType.value === 1) {
        getEventComment()
      } else if (commentType.value === 2) {
        musicComment()
      } else if (commentType.value === 3) {
        albumCommet()
      } else if (commentType.value === 4) {
        mvsCommet()
      } else if (commentType.value === 0) {
        getAllComment()
      }
    } finally {

    }
  } else {
    if (loginAndRegisterRef.value) {
      loginAndRegisterRef.value.loginVisible = true
      loginAndRegisterRef.value.getQrKeyData()
    }
  }
}
// 点赞点击事件
const hanleClickLike = (commentId: number, liked: boolean) => {
  if (!liked) {
    // 还没被点赞
    likeParams.t = 1
  } else {
    likeParams.t = 0
  }
  if(commentType.value === 1){
    likeParams.threadId = id.value
  }
  likeParams.cid = commentId
  likeParams.id = id.value
  if (commentType.value === 1) {
    likeParams.type = 6
  } else if (commentType.value === 2) {
    likeParams.type = 0
  } else if (commentType.value === 3) {
    likeParams.type = 3
  } else if (commentType.value === 4) {
    likeParams.type = 5
  } else if (commentType.value === 0) {
    likeParams.type = 2
  }
  getCommentLikeData()
}
// 点赞
const getCommentLikeData = async () => {
  let cookie = localStorage.getItem('cookie')
  let obj = {
    cookie
  }
  if (cookie) {
    const res: any = await commentApi.commetLike({ ...likeParams, ...obj })
    if (res.code === 200) {
      if (likeParams.t === 1) {
        ElMessage({
          type: 'success',
          message: '点赞成功',
          duration: 2000
        })
      } else {
        ElMessage({
          type: 'success',
          message: '取消点赞成功',
          duration: 2000
        })
      }
    }
    if (commentType.value === 1) {
      getEventComment()
    } else if (commentType.value === 2) {
      musicComment()
    } else if (commentType.value === 3) {
      albumCommet()
    } else if (commentType.value === 4) {
      mvsCommet()
    } else if (commentType.value === 0) {
      getAllComment()
    }
  } else {
    if (loginAndRegisterRef.value) {
      loginAndRegisterRef.value.loginVisible = true
      loginAndRegisterRef.value.getQrKeyData()
    }
  }

}
onMounted(() => {
})
</script>
<style lang="scss" scoped>
.comment_container {

  .my_comment_wrapper {
    display: flex;
    margin-top: 30px;

    .left_user_avatar {
      width: 50px;
      height: 50px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .right_text_input {
      flex: 1;
      margin-left: 14px;
    }
  }

  .foucs_comment_wrapper {
    margin-top: 50px;

    .foucs_title {
      color: #333;
      border-bottom: 1px solid #cfcfcf;
      padding-bottom: 10px;
      font-size: 12px;
      font-weight: 700;
    }

    .user_comment_item {
      display: flex;
      padding: 15px 0;
      border-bottom: 1px dotted #ccc;

      &:last-child {
        border-bottom: none;
      }

      .left_user_comment_avatar {
        width: 50px;
        height: 50px;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .right_user_comment_contnent {
        margin-left: 10px;
        flex: 1;

        .top_info {
          font-size: 12px;

          .comment_text {
            color: #333;
            line-height: 1.5;
          }
        }

        .middle_info {
          font-size: 12px;
          line-height: 20px;
          padding: 8px 19px;
          margin-top: 10px;
          background: #f4f4f4;
          border: 1px solid #dedede;
        }

        .bottom_info {
          display: flex;
          justify-content: space-between;
          margin-top: 20px;
          font-size: 12px;

          .left_time {
            color: #999;
          }

          .right_esb_wrap {
            display: flex;
            align-items: center;
            font-size: 14px;

            .right_esb {
              display: flex;
              align-items: center;

              span {
                margin-left: 4px;
                color: #333;
              }
            }
          }
        }
      }
    }
  }
}

.btn_comment {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>